package cn.simon.free.redis.mq.component;

import cn.simon.free.redis.mq.enums.ConsumerType;
import cn.simon.free.redis.mq.model.Message;
import cn.simon.free.redis.redisson.common.RedissonCommon;
import org.redisson.api.RScoredSortedSet;
import org.springframework.stereotype.Component;

/**
 * redisson message 工具
 *
 * @author simon
 * @date 2021/7/2 11:18
 * @copyright:
 * @modifier
 * @motto a no talent, people who have to study hard
 */
@Component
public class RedisMessageSupport extends RedissonCommon {

    /**
     * 从桶里面获取数据
     *
     * @param key
     * @return
     */
    public Message getByBucket(String key) {
        RScoredSortedSet<Message> scoredSortedSet = redissonClient.getScoredSortedSet(key);
        if (scoredSortedSet.size() == 0) {
            return null;
        }
        return scoredSortedSet.first();
    }

    /**
     * 从桶里面移除并获取数据
     *
     * @param key
     * @return
     */
    public Message getByBucketPoll(String key) {
        RScoredSortedSet<Message> scoredSortedSet = redissonClient.getScoredSortedSet(key);
        if (scoredSortedSet.size() == 0) {
            return null;
        }
        return scoredSortedSet.pollFirst();
    }

    /**
     * 判断你是否为集群
     *
     * @param key
     * @param consumerType
     * @return
     */
    public Message isClusterAndGetMessage(String key, ConsumerType consumerType) {
        if (ConsumerType.CLUSTER.equals(consumerType)) {
            return getByBucketPoll(key);
        } else {
            return getByBucket(key);
        }
    }

    public boolean isCluster(ConsumerType consumerType) {
        return ConsumerType.CLUSTER.equals(consumerType);
    }

    /**
     * 新增记录
     *
     * @param key
     * @param message
     * @param delayTime
     * @return
     */
    public boolean push(String key, Message message, Long delayTime) {
        RScoredSortedSet<Message> scoredSortedSet = redissonClient.getScoredSortedSet(key);
        return scoredSortedSet.add(delayTime, message);
    }

    /**
     * 删除记录
     *
     * @param key
     * @param message
     * @return
     */
    public boolean delete(String key, Message message) {
        RScoredSortedSet<Message> scoredSortedSet = redissonClient.getScoredSortedSet(key);
        return scoredSortedSet.remove(message);
    }

}
